package com.haha.Actions;

import com.haha.Beans.Book;
import com.haha.Common.Result;
import com.haha.Services.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// 此处的action即为controller，用于处理请求跳转等
@RestController     // 使用@RestController注解来表明这个类将使用HTTP响应体
@RequestMapping("/book")    // @RequestMapping注解定义了API的基础路径
public class BookAction {
    private final IBookService bookService;
    public BookAction(IBookService bookService) {
        this.bookService = bookService;
    }

    @RequestMapping("/books")
    List<Book> getBooks(){
        return this.bookService.getBooks();
    }
    @RequestMapping("booksCount")
    Integer getBooksCount(){
        return this.bookService.getBooksCount();
    }

    @GetMapping("/books/getBook/{id}")
    public ResponseEntity<Book> getBook(@PathVariable Integer id){
        Book book = this.bookService.selectBookById(id);
        if (book != null){
            return ResponseEntity.ok(book);
        }
        return ResponseEntity.notFound().build();
    }

    @PostMapping("/addBook")
    public ResponseEntity<Void> addBook(@RequestBody Book record){       // @RequestBody注解用于将HTTP请求体中的JSON数据绑定到Book对象上
         this.bookService.insertBook(record);
         Book newbook = this.bookService.selectBookById(record.getBookId());
         if (newbook != null){
             return ResponseEntity.ok().build();
         }
        return ResponseEntity.notFound().build();
    }

    @DeleteMapping("/deleteBook/{id}")
    public ResponseEntity<Void> deleteBook(@PathVariable Integer id){
        Book book = this.bookService.selectBookById(id);
        if (book != null){
            Integer affectedRows = this.bookService.deleteBook(id);
            if (affectedRows >0){
                return ResponseEntity.ok().build();
            } else if (affectedRows == 0){
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.internalServerError().build();
        }
        return ResponseEntity.notFound().build();
    }

    @PutMapping("/updateBook/{id}")
    public ResponseEntity<Book> updateBook(@PathVariable Integer id, @RequestBody Book record){
        if (this.bookService.selectBookById(id) != null){
            Book updateBook = this.bookService.updateBook(id, record);
            if (updateBook != null){
                return ResponseEntity.ok(updateBook);
            }
            return ResponseEntity.badRequest().body(null);
        }
        return ResponseEntity.notFound().build();
    }
}
